package com.zjcloud.jwgl.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.zjcloud.common.annotation.Log;
import com.zjcloud.common.core.controller.BaseController;
import com.zjcloud.common.core.domain.AjaxResult;
import com.zjcloud.common.enums.BusinessType;
import com.zjcloud.jwgl.domain.JwglScheduleTask;
import com.zjcloud.jwgl.service.IAcScheduleTaskService;
import com.zjcloud.jwgl.service.IAcScheduleAlgorithmConfigService;
import com.zjcloud.common.utils.poi.ExcelUtil;
import com.zjcloud.common.core.page.TableDataInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 智能排课任务Controller
 * 
 * @author zjcloud
 * @date 2024-12-19
 */
@RestController
@RequestMapping("/jwgl/schedule/task")
public class JwglAcScheduleTaskController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(JwglAcScheduleTaskController.class);

    @Autowired
    private IAcScheduleTaskService acScheduleTaskService;

    @Autowired
    private IAcScheduleAlgorithmConfigService algorithmConfigService;

    /**
     * 查询智能排课任务列表
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:list')")
    @GetMapping("/list")
    public TableDataInfo list(JwglScheduleTask acScheduleTask)
    {
        startPage();
        List<JwglScheduleTask> list = acScheduleTaskService.selectAcScheduleTaskList(acScheduleTask);
        return getDataTable(list);
    }

    /**
     * 导出智能排课任务列表
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:export')")
    @Log(title = "智能排课任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, JwglScheduleTask acScheduleTask)
    {
        List<JwglScheduleTask> list = acScheduleTaskService.selectAcScheduleTaskList(acScheduleTask);
        ExcelUtil<JwglScheduleTask> util = new ExcelUtil<JwglScheduleTask>(JwglScheduleTask.class);
        util.exportExcel(response, list, "智能排课任务数据");
    }

    /**
     * 获取智能排课任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(acScheduleTaskService.selectAcScheduleTaskById(id));
    }

    /**
     * 新增智能排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:add')")
    @Log(title = "智能排课任务", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody JwglScheduleTask acScheduleTask)
    {
        return toAjax(acScheduleTaskService.insertAcScheduleTask(acScheduleTask));
    }

    /**
     * 修改智能排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:edit')")
    @Log(title = "智能排课任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody JwglScheduleTask acScheduleTask)
    {
        return toAjax(acScheduleTaskService.updateAcScheduleTask(acScheduleTask));
    }

    /**
     * 删除智能排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:remove')")
    @Log(title = "智能排课任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(acScheduleTaskService.deleteAcScheduleTaskByIds(ids));
    }

    /**
     * 创建排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:create')")
    @Log(title = "创建排课任务", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult createTask(@RequestBody Map<String, Object> params)
    {
        try {
            String taskName = (String) params.get("taskName");
            String semester = (String) params.get("semester");
            Long semesterId = params.get("semesterId") != null ? 
                Long.valueOf(params.get("semesterId").toString()) : null;
            
            if (taskName == null || taskName.trim().isEmpty()) {
                return error("任务名称不能为空");
            }
            if (semester == null || semester.trim().isEmpty()) {
                return error("学期不能为空");
            }
            
            Long taskId = acScheduleTaskService.createScheduleTask(taskName, semesterId, semester, params);
            if (taskId != null) {
                return success("创建任务成功");
            } else {
                return error("创建任务失败");
            }
        } catch (Exception e) {
            log.error("创建排课任务失败: {}", e.getMessage(), e);
            return error("创建任务失败: " + e.getMessage());
        }
    }

    /**
     * 启动排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:start')")
    @Log(title = "启动排课任务", businessType = BusinessType.UPDATE)
    @PostMapping("/start/{taskId}")
    public AjaxResult startTask(@PathVariable Long taskId)
    {
        try {
            boolean result = acScheduleTaskService.startScheduleTask(taskId);
            if (result) {
                return success("启动任务成功");
            } else {
                return error("启动任务失败");
            }
        } catch (Exception e) {
            log.error("启动排课任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return error("启动任务失败: " + e.getMessage());
        }
    }

    /**
     * 停止排课任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:stop')")
    @Log(title = "停止排课任务", businessType = BusinessType.UPDATE)
    @PostMapping("/stop/{taskId}")
    public AjaxResult stopTask(@PathVariable Long taskId)
    {
        try {
            boolean result = acScheduleTaskService.stopScheduleTask(taskId);
            if (result) {
                return success("停止任务成功");
            } else {
                return error("停止任务失败");
            }
        } catch (Exception e) {
            log.error("停止排课任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return error("停止任务失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务状态
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:query')")
    @GetMapping("/status/{taskId}")
    public AjaxResult getTaskStatus(@PathVariable Long taskId)
    {
        try {
            Map<String, Object> status = acScheduleTaskService.getTaskStatus(taskId);
            return success(status);
        } catch (Exception e) {
            log.error("获取任务状态失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return error("获取任务状态失败: " + e.getMessage());
        }
    }

    /**
     * 根据学期查询任务列表
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:list')")
    @GetMapping("/semester/{semester}")
    public AjaxResult getTasksBySemester(@PathVariable String semester)
    {
        try {
            List<JwglScheduleTask> tasks = acScheduleTaskService.selectTasksBySemester(semester);
            return success(tasks);
        } catch (Exception e) {
            log.error("根据学期查询任务失败，学期: {}, 错误: {}", semester, e.getMessage(), e);
            return error("查询任务失败: " + e.getMessage());
        }
    }

    /**
     * 查询正在执行的任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:list')")
    @GetMapping("/running")
    public AjaxResult getRunningTasks()
    {
        try {
            List<JwglScheduleTask> tasks = acScheduleTaskService.selectRunningTasks();
            return success(tasks);
        } catch (Exception e) {
            log.error("查询正在执行的任务失败: {}", e.getMessage(), e);
            return error("查询正在执行的任务失败: " + e.getMessage());
        }
    }

    /**
     * 获取任务执行历史
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:list')")
    @GetMapping("/history")
    public AjaxResult getTaskHistory(
            @RequestParam(required = false) String semester,
            @RequestParam(defaultValue = "10") Integer limit)
    {
        try {
            List<JwglScheduleTask> tasks = acScheduleTaskService.getTaskHistory(semester, limit);
            return success(tasks);
        } catch (Exception e) {
            log.error("获取任务历史失败，学期: {}, 错误: {}", semester, e.getMessage(), e);
            return error("获取任务历史失败: " + e.getMessage());
        }
    }

    /**
     * 更新任务进度
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:edit')")
    @PostMapping("/progress/{taskId}")
    public AjaxResult updateProgress(@PathVariable Long taskId, @RequestParam Integer progress)
    {
        try {
            boolean result = acScheduleTaskService.updateTaskProgress(taskId, progress);
            if (result) {
                return success("更新进度成功");
            } else {
                return error("更新进度失败");
            }
        } catch (Exception e) {
            log.error("更新任务进度失败，任务ID: {}, 进度: {}, 错误: {}", taskId, progress, e.getMessage(), e);
            return error("更新进度失败: " + e.getMessage());
        }
    }

    /**
     * 完成任务
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:edit')")
    @PostMapping("/complete/{taskId}")
    public AjaxResult completeTask(@PathVariable Long taskId, @RequestBody Map<String, Object> resultData)
    {
        try {
            boolean result = acScheduleTaskService.completeTask(taskId, resultData);
            if (result) {
                return success("完成任务成功");
            } else {
                return error("完成任务失败");
            }
        } catch (Exception e) {
            log.error("完成任务失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return error("完成任务失败: " + e.getMessage());
        }
    }

    /**
     * 标记任务失败
     */
    @PreAuthorize("@ss.hasPermi('jwgl:schedule:task:edit')")
    @PostMapping("/fail/{taskId}")
    public AjaxResult failTask(@PathVariable Long taskId, @RequestParam String errorMessage)
    {
        try {
            boolean result = acScheduleTaskService.failTask(taskId, errorMessage);
            if (result) {
                return success("标记任务失败成功");
            } else {
                return error("标记任务失败失败");
            }
        } catch (Exception e) {
            log.error("标记任务失败失败，任务ID: {}, 错误: {}", taskId, e.getMessage(), e);
            return error("标记任务失败失败: " + e.getMessage());
        }
    }
}